import axios from 'axios'
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import router from "@/router";
// import { getToken } from '@/utils/auth'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
request.interceptors.request.use(
  (config) => {
    const token = store.getters.token;
    if (token) {
      config.headers.Authorization =token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
request.interceptors.response.use(
  (response) => {
    // const { data, message, success } = response.data;
    if (response.data) {
      // Message.success('登录成功')
      return response.data
    } else { 
      Message.error(response.data.msg)
      return Promise.reject(new Error(response.data.msg));
    }
   
  },
  (error) => {
    if (error.response.status === 401) {
      Message.warning("token过期，请重新登录");
      store.dispatch("user/logout");
      router.push("/login");
    } else {
      error.response.data?  Message.error(error.response.data): Message.error(error.response);
      // console.log(error.response);
    }
    return Promise.reject(error);
  }
);

export default request;
